package org.example.stockdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.stockdemo.entity.Stock;
import org.example.stockdemo.mapper.StockMapper;
import org.example.stockdemo.service.StockService;
import org.example.stockdemo.service.TencentStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private TencentStockService tencentStockService;


    //    批量保存股票数据
    @Override
    public boolean saveStocks(List<Stock> stocks) {
        if (CollectionUtils.isEmpty(stocks)){
            return false;
        }
        // 遍历股票信息，补充关键词作为搜索词
        for (Stock stock : stocks) {

        }

        return saveBatch(stocks);
    }

    @Override
    public List<Stock> search(String keyword) throws IOException {
        // 根据关键词查询数据库
        List<Stock> searchList = tencentStockService.search(keyword);
        if (CollectionUtils.isNotEmpty(searchList)){
            // 提取code、name ，根据code 检索是否在表里已存在，不存在则保存
            Map<String, Stock> codeNameMap = searchList.stream().collect(Collectors.toMap(Stock::getCode, Function.identity()));
            List<Stock> notExistCode = stockMapper.selectList(new LambdaQueryWrapper<Stock>().notIn(Stock::getCode, codeNameMap.keySet()));
            List<Stock> saveList=new ArrayList<>();
            for (Stock stock : notExistCode) {
                saveList.add(codeNameMap.get(stock.getCode()));
            }
            saveBatch(saveList);
        }
        return searchList;
    }

}